package faceb.server.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;

import faceb.server.dao.NewsDao;
import faceb.server.dao.NewspicDao;
import faceb.server.model.AjaxResponse;
import faceb.server.model.News;
import faceb.server.model.NewsPic;
import faceb.server.model.User;
import faceb.server.service.NewsService;
import faceb.server.util.CharSetUtil;
import faceb.server.util.ServerFinal;

@Controller
public class NewsController {

	private Logger logger = LoggerFactory.getLogger(NewsController.class);

	@Resource(name = "newsService")
	private NewsService newsService;

	@Resource(name = "newspicDao")
	private NewspicDao newspicDao;

	@Resource(name = "newsDao")
	private NewsDao newsDao;

	private Gson gson = new Gson();

	@RequestMapping(value = "/news/public", method = RequestMethod.POST)
	@ResponseBody
	private String publicNews(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {

		/*
		 * Map<String, Object> paramsAndFiles = UploadUtils
		 * .getUploadFilesAndParams(req); Map<String, String> params =
		 * (Map<String, String>) paramsAndFiles .get("params");
		 */
		Map<String, String> params = new HashMap<String, String>();
		params.put("topic", req.getParameter("topic"));
		params.put("title", req.getParameter("title"));
		params.put("content", req.getParameter("content"));
		String userid = ((User) req.getSession().getAttribute("user"))
				.getU_id();
		List<String> filePaths = (List<String>) req.getSession().getAttribute(
				userid + "upload");
		req.getSession().removeAttribute(userid + "upload"); //移除session
		List<File> files = new ArrayList<File>();
		if (filePaths != null)
			for (String filePath : filePaths) {
				files.add(new File(filePath));
			}
		String resultMes = newsService.publicNews(params, files, req);

		return CharSetUtil.getRespBodyStr(resultMes);
	}

	@RequestMapping(value = "/publicNews")
	private String publicNewsPage() {
		return "publicnews";
	}

	@RequestMapping("/news/{newsid}")
	@ResponseBody
	private String getNewsByNewsId(@PathVariable("newsid") String newsid,
			HttpServletResponse resp) {

		Map<String, Object> newsObject = newsService.getNewsByNewsId(newsid);
		AjaxResponse ar = new AjaxResponse();
		ar.setStatus(ServerFinal.SUCCESS_CODE);
		ar.setInfo(ServerFinal.SUCCESS_INFO);
		ar.setData(newsObject);
		return CharSetUtil.getRespBodyStr(gson.toJson(ar));
	}

	@RequestMapping("/pics/{picId}")
	public void getPicsById(@PathVariable("picId") String picId,
			HttpServletResponse resp) throws Exception {

		NewsPic newspic = newspicDao.getNewspicByPicId(picId);

		OutputStream os = resp.getOutputStream();
		if (newspic == null) {
			os.write("no such pic".getBytes());
			os.close();
			return;
		}
		Map<String,Object> news = newsDao.getNewsByNewsId(newspic.getNp_n_id());
		File picFile = Paths.get(ServerFinal.RESOURCE_DIR, (String)news.get("n_u_id"),
				"pics", newspic.getNp_name()).toFile();
		FileInputStream fis = new FileInputStream(picFile);
		byte b[] = new byte[fis.available()];
		fis.read(b);
		os.write(b);
		os.close();
	}

	@RequestMapping("/news/users/{userid}")
	@ResponseBody
	private String getNewsByUserId(@PathVariable("userid") String userid,
			HttpServletResponse resp) {

		AjaxResponse ar = new AjaxResponse();
		List<Map<String, Object>> newsObjects = newsService
				.getNewsByUserId(userid);
		ar.setStatus(ServerFinal.SUCCESS_CODE);
		ar.setInfo(ServerFinal.SUCCESS_INFO);
		ar.setData(newsObjects);

		return CharSetUtil.getRespBodyStr(gson.toJson(ar));

	}

	@RequestMapping("/newsbefore/time/{timeStr}/count/{countStr}")
	@ResponseBody
	private String getNewsBeforeTime(@PathVariable("timeStr") String timeStr,
			@PathVariable("countStr") String countStr, HttpServletResponse resp) {

		AjaxResponse ar = new AjaxResponse();
		if (!timeStr.matches("\\d+") || !countStr.matches("\\d+")) {
			return CharSetUtil.getRespBodyStr(gson.toJson(ar));
		}
		long time = Long.parseLong(timeStr);
		int count = Integer.parseInt(countStr);
		List<Map<String, Object>> newsObjects = newsService.getNewsBeforeTime(
				time, count);
		ar.setStatus(ServerFinal.SUCCESS_CODE);
		ar.setInfo(ServerFinal.SUCCESS_INFO);
		ar.setData(newsObjects);

		return CharSetUtil.getRespBodyStr(gson.toJson(ar));
	}

	@RequestMapping("/tpl/news/detail/{newsid}")
	private String detailNews(@PathVariable("newsid") String newsid) {

		return "detail";
	}

	@RequestMapping("/newsafter/time/{timeStr}/count/{countStr}")
	@ResponseBody
	private String getNewsAfterTime(@PathVariable("timeStr") String timeStr,
			@PathVariable("countStr") String countStr, HttpServletResponse resp) {

		AjaxResponse ar = new AjaxResponse();
		if (!timeStr.matches("\\d+") || !countStr.matches("\\d+")) {
			return CharSetUtil.getRespBodyStr(gson.toJson(ar));
		}
		long time = Long.parseLong(timeStr);
		int count = Integer.parseInt(countStr);
		List<Map<String, Object>> newsObjects = newsService.getNewsAfterTime(
				time, count);
		ar.setStatus(ServerFinal.SUCCESS_CODE);
		ar.setInfo(ServerFinal.SUCCESS_INFO);
		ar.setData(newsObjects);

		return CharSetUtil.getRespBodyStr(gson.toJson(ar));
	}
	
	@RequestMapping("/news/like/{newId}")
	@ResponseBody
	private String getNewsAfterTime(@PathVariable("newId") String newsId ,HttpServletResponse resp) {

		AjaxResponse ar = new AjaxResponse();
		int result = newsDao.newsZan(newsId);
		
		if(result==1){
		ar.setStatus(ServerFinal.SUCCESS_CODE);
		ar.setInfo(ServerFinal.SUCCESS_INFO);
		}

		return CharSetUtil.getRespBodyStr(gson.toJson(ar));
	}
}
